import { NodeProps } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import { CaretRightOutlined } from '@ant-design/icons'
import { Collapse, theme } from 'antd'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import { getLoopDefaultParams } from './default'
import OutputCont from './components/OutputCont'
import InputCont from './components/InputCont'
import RunDrawer from '../components/RunDrawer'
import { useSourceOptions } from '@/pages/workflow/hooks/use-source-options'

const LoopPanel: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables, setFlowVariables } = useWorkFlowStore()
  const { token } = theme.useToken()
  const [info, setInfo] = useState({ ...getLoopDefaultParams() })
  const { options } = useSourceOptions(info)
  const [isLoaded, setIsLoaded] = useState(false)
  
  const editData = (e: any) => {
    const obj = { ...info, ...e }
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
  }

  const [runDrawerHid, setrunDrawerHid] = useState(false)
  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
  
      setInfo(obj)
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }

      setIsLoaded(true)
    }
  }, [flowVariables])

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: {
      marginBottom: 5,
      background: token.colorFillAlter,
      borderRadius: token.borderRadiusLG,
      border: 'none'
    }
  })

  const inputItems = [
    createCollapseItem(
      '1',
      <CollapseNodeComponent title="输入" />,
      <InputCont info={info} editData={editData} />
    )
  ]

  const outputItems = [
    createCollapseItem(
      '2',
      <CollapseNodeComponent title="输出" />,
      <OutputCont info={info} editData={editData} />
    )
  ]

  const collapseItems = [
    { key: '1', items: inputItems },
    //{ key: '2', items: outputItems }
  ]

  const collapseProps = {
    bordered: false,
    expandIcon: ({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />,
    style: { background: token.colorBgContainer }
  }

  const renderCollapse = (item: any) => (
    <div className="mt-1" key={item.key}>
      <Collapse {...collapseProps} defaultActiveKey={[item.key]} items={item.items} />
    </div>
  )

  return (
    <div className="workflow-common-panel flexCol caseOverFlowY">
      {/* <span className="lim_title">对数组进行迭代处理</span> */}
      {isLoaded && collapseItems.map(renderCollapse)}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(LoopPanel)